package com.changge.generator.controller;

import com.changge.common.core.domain.response.PageResult;
import com.changge.common.core.domain.response.Result;
import com.changge.common.core.utils.ServletUtil;
import com.changge.generator.dto.GenerateOptionDTO;
import com.changge.generator.query.GenerateQuery;
import com.changge.generator.service.IGenerateLogService;
import com.changge.generator.service.IGenerateService;
import com.changge.generator.vo.TableDataVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 代码生成控制器
 *
 * @author zhangrongkang
 * @since 2024/1/9
 */
@Tag(name = "代码生成控制器")
@RestController
@RequestMapping("/admin/generator")
public class GenerateController {

    @Autowired
    private IGenerateService generateService;

    @Autowired
    private IGenerateLogService generateLogService;

    @Operation(summary = "分页获取数据库表")
    @PostMapping("/listTable")
    public Result<PageResult<TableDataVO>> listTable(@RequestBody GenerateQuery generateQuery) {
        return Result.ok(generateService.listTable(generateQuery));
    }

    @Operation(summary = "预览代码")
    @PostMapping("/preview")
    public Result<Map<String, String>> preview(@RequestBody GenerateOptionDTO generateOptionDTO) {
        Map<String, String> result = generateService.preview(generateOptionDTO);
        return Result.ok(result);
    }

    @Operation(summary = "下载代码")
    @PostMapping("/download")
    public void download(@RequestBody GenerateOptionDTO generateOptionDTO) {
        byte[] result = generateService.download(generateOptionDTO);
        ServletUtil.setZipServletResponse(result);
        // 保存当前生成数据
        generateLogService.save(generateOptionDTO);
    }

}
